﻿/**
 *    Copyright 2006 - 2011 Opera Software ASA
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 **/


var OperaDBLclickMenuController = function()
{
    var is_selection = false;
    var down_event = null;
    var selection = getSelection();
    var range = null;

    const POW = Math.pow;

    var distance = function(ev1, ev2)
    {
        return POW(POW(ev1.clientX - ev2.clientX, 2) +
                   POW(ev1.clientY - ev2.clientY, 2), .5);
    };

    var mousedown = function(event)
    {
        is_selection = !selection.isCollapsed;
        down_event = event;
    };

    var re_add_range = function() 
    {
        if (selection && range)
        {
            selection.addRange(range);
            range = null;
        }
    };

    var mouseup = function(event)
    {
        if (down_event && event.target == down_event.target &&
            distance(down_event, event) < 3 &&
            !is_selection && !selection.isCollapsed)
        {
            range = selection.getRangeAt(0);
            selection.removeAllRanges();
            setTimeout(re_add_range, 0);
        }
    };

    document.addEventListener('mousedown', mousedown, true);
    document.addEventListener('mouseup', mouseup, true);
};
